<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>addEventListener this</title>
    <link rel="stylesheet" href="../../styles/normalize.css" />
  </head>
  <body>
    <button id="example-button" class="test">
      You have not clicked this button.
    </button>
    <button id="scope-button" class="test">scope button.</button>
    <table id="my_table" onclick="console.log(this.id);">
      <!-- `this` 指向 table 元素；输出 'my_table' -->
      <tr>
        <td id="t1">one</td>
      </tr>
      <tr>
        <td id="t2">two</td>
      </tr>
    </table>
    <table id="my_table2" onclick="logID()">
      <!-- 被调用时，`this` 指向全局（window）对象 -->
      <tr>
        <td id="t1">one</td>
      </tr>
      <tr>
        <td id="t2">two</td>
      </tr>
    </table>

    <script>
      function logID() {
        console.log(this.id);
      }
      const my_element = document.getElementById("example-button");
      my_element.addEventListener("click", function (e) {
        console.log(this.className); // 输出 my_element 的 className
        console.log(e.currentTarget === this); // 输出 `true`
      });

      my_element.addEventListener("click", (e) => {
        console.log(this.className); // 警告：`this` 并不指向 `my_element`
        console.log(e.currentTarget === this); // 输出 `false`
      });

      const Something = function (element) {
        // |this| is a newly created object
        this.name = "Something Good";
        this.onclick1 = function (event) {
          console.log(this.name); // undefined, as |this| is the element
        };

        this.onclick2 = function (event) {
          console.log(this.name); // 'Something Good', as |this| is bound to newly created object
        };

        // bind causes a fixed `this` context to be assigned to onclick2
        this.onclick2 = this.onclick2.bind(this);

        element.addEventListener("click", this.onclick1, false);
        element.addEventListener("click", this.onclick2, false); // Trick
      };
      const s = new Something(document.body);

      const myButton = document.getElementById("scope-button");
      let someString = "Data";

      myButton.addEventListener("click", () => {
        console.log(someString); // 预期输出：'Data'

        someString = "Data Again";
      });

      console.log(someString); // 预期输出：'Data'（不可能是 'Data Again'）
    </script>
  </body>
</html>
